package com.hopes.bizz.risk.tenant.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hopes.bizz.common.core.util.StringUtils;
import com.hopes.bizz.risk.setting.entity.RiskSafetyWarningLabelEntity;
import com.hopes.bizz.risk.setting.service.RiskSafetyWarningLabelService;
import com.hopes.boss.admin.api.dto.SysFileUploadDTO;
import com.hopes.boss.admin.api.entity.SysTenant;
import com.hopes.boss.admin.api.feign.RemoteFileService;
import com.hopes.boss.common.core.constant.SecurityConstants;
import com.hopes.boss.common.data.tenant.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/8/14 14:28
 * @Description:
 */
@Slf4j
//@Service
public class RiskSafetyTenantInitServiceImpl {

    @Autowired
    private RiskSafetyWarningLabelService safetyWarningLabelService;

    @Resource
    private RemoteFileService remoteFileService;

    public String getName() {
        return "初始化安全警示标识配置";
    }

    public void init(SysTenant tenant) {
        Long tenantId = tenant.getId();

        List<RiskSafetyWarningLabelEntity> list = safetyWarningLabelService.list(Wrappers.<RiskSafetyWarningLabelEntity>lambdaQuery().eq(RiskSafetyWarningLabelEntity::getTenantId, TenantContextHolder.getAdminTenantId()));
        for (RiskSafetyWarningLabelEntity entity : list) {
            entity.setId(null);
            // 样例：/admin/sys-file/tenant-1/e251c9146ec1452f94e6107877dd07ff.png
            String bucketName = entity.getImage().split(StringUtils.SLASH)[entity.getImage().split(StringUtils.SLASH).length - 2];
            String imgName = entity.getImage().split(StringUtils.SLASH)[entity.getImage().split(StringUtils.SLASH).length - 1];

            SysFileUploadDTO sysFileUploadDTO = remoteFileService.copyFile(bucketName, imgName, TenantContextHolder.getTenantBucketName(tenantId), SecurityConstants.FROM_IN);
            if (sysFileUploadDTO.getMsg() == null) {
                entity.setImage(sysFileUploadDTO.getUrl());
            } else {
                log.error("初始化安全警示标识配置，上传图片时出错，错误信息：{}", sysFileUploadDTO.getMsg());
            }
            entity.setTenantId(tenantId);
        }
        safetyWarningLabelService.saveBatch(list);
    }
}
